﻿using EquipmentAlarmSystem.Controllers;
using EquipmentAlarmSystem.Service.Library;
using EquipmentAlarmSystem.Service.Models;
using EquipmentAlarmSystem.Service.Models.Enum;

namespace EquipmentAlarmSystem.Service.ContentPushUnit;

/// <summary>
/// 信息推送服务
/// </summary>
public static class InformationPushService
{
    /// <summary>
    /// 日志记录
    /// </summary>
    static Logging logging = new("InformationPushService", false);

    /// <summary>
    /// 消息队列
    /// </summary>
    private static Queue<InformationTransmission> _taskQueue = new();

    /// <summary>
    /// 发送任务状态
    /// </summary>
    private static bool sendTaskStatus = false;

    /// <summary>
    /// 添加消息
    /// </summary>
    /// <param name="messageType"></param>
    /// <param name="contacts"></param>
    /// <param name="message"></param>
    public static void Add(MessageType messageType, List<string> contacts, string message)
    {
        //检查接收人是否存在
        if (contacts is null || contacts.Count < 1)
        {
            return;
        }

        //消息添加队列
        foreach (var item in contacts)
        {
            //构建信息
            InformationTransmission information = new();
            information.Contacts = item;
            information.Message = message;
            information.Type = messageType;
            //添加队列
            _taskQueue.Enqueue(information);
        }

        //检查是否存在发送任务
        if (sendTaskStatus == false)
        {
            //发送任务启动
            sendTaskStatus = true;
            new Task(SendQueue).Start();
        }
    }

    /// <summary>
    /// 发送任务
    /// </summary>
    private static void SendQueue()
    {
        logging.Info($"推送任务开始");
        while (sendTaskStatus)
        {
            if (_taskQueue.Count <= 0)
            {
                break; //无任务 退出
            }
            //检查短信终端连接
            if (SmsAlarmConnection.AlarmStatus)
            {
                //获取队列信息
                InformationTransmission information = _taskQueue.Dequeue();

                if (information.Type == MessageType.Sms)
                {
                    SmsAlarmConnection.SendSms(information.Contacts, information.Message);
                    logging.Info($"to:{information.Contacts};content:{information.Message.Replace("\n", "")}");
                }
                if (information.Type == MessageType.Call)
                {
                    SmsAlarmConnection.SendCall(information.Contacts, information.Message);
                    logging.Info($"to:{information.Contacts};content:{information.Message.Replace("\n", "")}");
                }
                //间隔1秒
                Thread.Sleep(1000);
            }
            else
            {
                Logging loggings = new("InformationPushService");
                //无短信终端               
                if (Basics.Config.ServiceType == ServerType.Slave)
                {
                    //尝试联系主站
                    loggings.Info($"无短信终端，尝试通过主站执行任务：剩余{_taskQueue.Count}条");
                    //获取队列信息
                    InformationTransmission information = _taskQueue.Dequeue();
                    // 准备POST数据  
                    var data = new SendingMessages()
                    {
                        To = information.Contacts,
                        Content = information.Message
                    };
                    //数据发送
                    if (information.Type == MessageType.Sms)
                    {
                        _ = Basics.HttpPostAsync($"{Basics.Config.ServiceAddress}/AlarmSending/SendSms", data);
                    }
                    if (information.Type == MessageType.Call)
                    {
                        loggings.Info($"无短信终端，拨号任务丢弃！");
                        //_ = Basics.HttpPostAsync($"{Basics.Config.ServiceAddress}/AlarmSending/MakingPhoneCalls", data);
                    }
                    //间隔1秒
                    Thread.Sleep(1000);
                }
                else
                {
                    loggings.Info($"服务主站运行，无短信终端，系统清空当前任务：{_taskQueue.Count}条");
                    _taskQueue.Clear();//清空任务
                }
            }
        }
        //退出发送任务
        sendTaskStatus = false;
        logging.Info($"推送任务结束");
    }
}
